/*
 * ===========================================================================
 *
 *      Filename: pthread_locker.c
 *   Description: implement locker with pthread locker
 *        Author: Ye wenhao, wenhaoye@126.com
 *  Organization: 
 *
 * ===========================================================================
 */
#include "pthread_locker.h"
#include <pthread.h>
#include "def.h"

static int pthread_locker_lock(locker_t *self)
{
    pthread_mutex_t mutex;
    memcpy(&mutex, self->priv, sizeof(mutex));
    return pthread_mutex_lock(&mutex);
}

static int pthread_locker_unlock(locker_t *self)
{
    pthread_mutex_t mutex;
    memcpy(&mutex, self->priv, sizeof(mutex));
    return pthread_mutex_unlock(&mutex);
}

static void pthread_locker_destroy(locker_t *self)
{
    pthread_mutex_t mutex;
    memcpy(&mutex, self->priv, sizeof(mutex));
    pthread_mutex_destroy(&mutex);
    safe_free(self);
}

static int pthread_locker_get(locker_t *self, void *buf, size_t size)
{
    memcpy(buf, self->priv, size);
    return 0;
}


locker_t *pthread_locker_create(void)
{
    locker_t *self = (locker_t *)MALLOC(sizeof(locker_t) + sizeof(pthread_mutex_t));
    if(self){
        self->lock = pthread_locker_lock;
        self->unlock = pthread_locker_unlock;
        self->destroy = pthread_locker_destroy;
        self->get = pthread_locker_get;
        
        pthread_mutex_t mutex;
        pthread_mutex_init(&mutex, NULL);
        memcpy(self->priv, &mutex, sizeof(mutex));
    }

    return self;
}
